package cn.cxq.learning.hashtable;

public class HashTable {

    private StudentLinkedList[] studentLinkedList;
    private int size;

    public HashTable(int size) {
        this.size = size;
        studentLinkedList = new StudentLinkedList[size];
        for (int i = 0; i < studentLinkedList.length; i++) {
            studentLinkedList[i] = new StudentLinkedList();
        }
    }

    public void add(Student student) {

        int index = getHash(student.id);//获取该插入的单链表的下标

        studentLinkedList[index].add(student);
    }

    public void list() {

        for (int i = 0; i < studentLinkedList.length; i++) {
            System.out.print("第" + i + "个链表：");
            studentLinkedList[i].list();
        }
    }

    public void delete(int id) {
        System.out.print("删除结果：");
        int index = getHash(id);
        studentLinkedList[index].delete(id);
    }

    public Student find(int id){
        int index = getHash(id);
        System.out.print("查找结果");
        return studentLinkedList[index].find(id);
    }

    public int getHash(int id) {
        return id % size;
    }
}

class StudentLinkedList {

    private Student head;

    public StudentLinkedList() {
        head = new Student(-1, "");
    }

    public void add(Student student) {

        Student temp = head;
        while (temp.next != null) temp = temp.next;
        temp.next = student;
    }

    public void list() {
        if (head.next == null) System.out.println("链表为空~~~");
        else {
            Student temp = head;
            while (temp.next != null) {
                temp = temp.next;
                System.out.print(temp + " ");
            }
            System.out.println();
        }
    }

    public void delete(int id) {
        Student temp = head;

        while (temp.next != null) {
            if (temp.next.id == id) {
                System.out.println(temp.next + "删除成功");
                temp.next = temp.next.next;
                return;
            }
            temp = temp.next;
        }

        System.out.println("未找到该id对应的学生，该id对应的学生不存在~~~");
    }

    public Student find(int id) {
        Student temp = head;
        while (temp.next!=null){
            temp=temp.next;
            if (temp.id==id) {
                System.out.println("学生信息：" + temp);
                return temp;
            }
        }
        System.out.println("未找到id为"+"的学生~~~");
        return null;
    }
}

class Student {

    int id;
    String name;
    //等等属性。。。。

    Student next; //下一个学生的指针

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
        this.next = null;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}